package com.beyond.core.codec;

import java.net.InetSocketAddress;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

public class MessageEncoder extends MessageToMessageEncoder<String> {

	//这里是广播的地址和端口
	private InetSocketAddress remoteAddress;
	
	public MessageEncoder(int remotePort) {
		remoteAddress = new InetSocketAddress("255.255.255.255", remotePort); //广播
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx, String msg, List<Object> list) throws Exception {
	   
     
		 byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
         ByteBuf buf = ctx.alloc().buffer(bytes.length);
         buf.writeBytes(bytes);
         DatagramPacket packet = new DatagramPacket(buf, remoteAddress);
         list.add(packet);
	}
}
